﻿using IPS.SP2013.DiagnosticsProvider;
using Microsoft.SharePoint;
using System;

namespace IPS.SP2013.Helper
{

    /// <summary>
    /// 
    /// </summary>
    public static class IPSSiteHelper
    {

        public static string GetSitePropertyBag(string siteUrl, string propertyName)
        {
            string value = string.Empty;

            try
            {
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    using (SPSite site = new SPSite(siteUrl))
                    {
                        if (site != null)
                        {
                            // Get root web in current site
                            SPWeb web = site.RootWeb;

                            if (web != null)
                            {
                                // Get property bag by name
                                var property = web.GetProperty(propertyName);

                                if (property != null)
                                {
                                    // Read property bag value
                                    value = property.ToString();
                                }
                                else
                                {
                                    LogProvider.WriteLogEntry(DiagnosticsProvider.Constants.CategoryNames.Warning,
                                                              "IPSSiteHelper.GetSitePropertyBag(): Unable to get property bag");
                                }
                            }
                            else
                            {
                                LogProvider.WriteLogEntry(DiagnosticsProvider.Constants.CategoryNames.Warning,
                                                          "IPSSiteHelper.GetSitePropertyBag(): Unable to get root web");
                            }
                        }
                        else
                        {
                            LogProvider.WriteLogEntry(DiagnosticsProvider.Constants.CategoryNames.Warning,
                                                      "IPSSiteHelper.GetSitePropertyBag(): Unable to get site");
                        }
                    }
                });
            }
            catch (Exception ex)
            {
                LogProvider.WriteLogEntry(DiagnosticsProvider.Constants.CategoryNames.Error,
                    "IPSSiteHelper.GetSitePropertyBag(): " + ex.Message);
            }

            return value;
        }

    }

}
